﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Text;
using System.Windows.Forms;
using DSAManager.Core;
using DSAManager.Models.Input;
using DSAManager.Utils;

namespace DSAManager
{
    public partial class FrmLogin : Form
    {
        public FrmLogin()
        {
            InitializeComponent();
        }

        private void btn_exit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btn_login_Click(object sender, EventArgs e)
        {
            if (txt_user.Text.Trim().Length == 0 || txt_password.Text.Trim().Length == 0)
            {
                MsgBox.Alert("账号/密码不能为空!");
                return;
            }
            UserLoginInfo loginInfo = new UserLoginInfo() {user = txt_user.Text, password = txt_password.Text};
            loginInfo.isrember = chk_remberMe.Checked;
            var result = Api.Login(loginInfo);
            if (result.ok)
            {
                if (loginInfo.isrember)
                {
                    string loginjson = JsonHelper.SerializeObject(loginInfo);
                    File.WriteAllText( Application.StartupPath + "\\.info",DesHelper.Encrypt(loginjson), Encoding.UTF8);    
                }
                
                AppContext.LoginInfo = loginInfo;
                this.DialogResult = System.Windows.Forms.DialogResult.OK;
                this.Close();
            }
            else
            {
                MsgBox.Alert(result.msg);
            }
            
        }

        private void FrmLogin_Load(object sender, EventArgs e)
        {
            try
            {
                string json =DesHelper.Decrypt(File.ReadAllText(Application.StartupPath + "\\.info", Encoding.UTF8));
                var obj = JsonHelper.DeserializeObject<UserLoginInfo>(json);
                if(obj.isrember)
                {
                    txt_user.Text = obj.user;
                    txt_password.Text = obj.password;
                    chk_remberMe.Checked = true;
                }
            }
            catch (Exception)
            {
                
                
            }
        }
    }



    
}
